<style lang=less scoped>
	@import "../../variables.less";
	@import "../../resource/common.less";

	@currentWidth: 550px;
	@attachWidth: unset;
	.info {
		line-height: 2;
		font-size: 14px;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		color: #FFF;
		margin-bottom: @middleSpace;

		.detail {
			width: 50%;
			padding-left: @smallSpace;

			&:nth-child(odd):before {
				content: "";
				display: block;
				width: 200%;
				position: absolute;
				left: 0;
				top: 0;
				height: 100%;
			}

			label {
				display: inline-block;
				width: 90px;
				text-align: justify;
				text-align-last: justify;
				float: left;

				+ * {
					display: block;
					margin-left: 100px;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;
				}
			}
		}
	}
</style>
<template>
	<div class="mainContent" style="top:100px">
		<Loading v-if="loading" />
		<template v-else-if="type !== 'distribution'">
			<div class="head">
				工单详情
			</div>
			<div class="info">
				<div class="detail"><label>关联元素</label><span :title="data.element">{{data.element||"暂无"}}</span></div>
				<div class="detail"><label>当前步骤</label><span>{{data.stepName||"暂无"}}</span></div>
				<div class="detail"><label>故障位置</label><span :title="errorSpaceString">{{errorSpaceString||"暂无"}}</span>
				</div>
				<div class="detail"><label>优先级</label><span>{{["特急","紧急","一般"][data.priority]}}</span></div>
				<div class="detail"><label>班组</label><span>{{templateName||"暂无"}}</span></div>
				<div class="detail"><label>创建日期</label><span>{{data.createTime|getTimeString}}</span></div>
				<div class="detail"><label>截止日期</label><span>{{data.deadline|getTimeString}}</span></div>
				<div class="detail"><label>关联文件</label>
					<operation-file-list :files=file />
				</div>
				<div class="detail"><label>服务态度</label><span>{{['不满意','满意','未评价'][data.attitude]}}</span></div>
				<div class="detail"><label>服务质量</label><span>{{['不满意','满意','未评价'][data.quality]}}</span></div>
				<div class="detail"><label>及时性</label><span>{{['不满意','满意','未评价'][data.timeliness]}}</span></div>
				<div class="detail"><label>负责人</label><span>{{data.principal||"暂无"}}</span></div>
			</div>
			<template v-if="$route.name==='operation'">
				<div class="head">
					工单处理
				</div>
				<component :is="type" ref="operation" />
			</template>
			<template v-else-if="spares.length>0">
				<div class="head">
					备品备件账单
				</div>
				<Table :columns="columns" :data="spares" :max-height="150" size="small" />
			</template>
			<div class="head">
				处理历史
			</div>
			<OperationStep :step="step" style="height: 80px;flex-grow: 1" />
			<div style="text-align: right;margin-top: 6px">
				<template v-if="$route.name==='operation'">
					<Button :key="i.value" :loading="loading" @click="submit(i.value)" ghost style="margin-left: 6px"
						v-for='i in btnList'>{{i.text}}
					</Button>
					<!-- <Button :loading="loading" @click="submit()" ghost style="margin-left: 6px">提交</Button> -->
				</template>
				<Button :loading="loading" @click="$router.go(-1)" ghost style="margin-left: 6px">返回</Button>
			</div>
		</template>
		<template v-else>
			<div class="head">
				分析分配
			</div>
			<div class="info">
				<div class="detail"><label>发起人</label><span>{{data.creator}}</span></div>
				<div class="detail"><label>发起时间</label><span>{{data.createTime|getTimeString}}</span></div>
				<div class="detail"><label>已上传文件</label><span>无</span></div>
			</div>
			<Distribution :btnList="btnList" :description="step[0].apart[0].description" :templateArray="templateArray"
				v-bind="data" />
		</template>
	</div>
</template>
<script lang=ts>
	import { Component, Vue, Watch } from "vue-property-decorator";
	import request from "../../request";
	import Loading from "@/components/loading/Loading.vue";
	import moment from "moment";
	import { Button, Message, Table } from "view-design";
	import normal from "@/components/repairSteps/normal.vue";
	import qs from "qs";
	import OperationStep from "@/components/repairSteps/operationStep.vue";
	import OperationFileList from "@/components/fileList/operationFileList.vue";
	import { Route } from "vue-router";

	interface step {
		name:string,
		apart?:{ operator:string, description:string, doc?:string[], voice?:string, completeTime?:string, how?:string }[]
	}

	interface file {
		filetype:string,
		fileurl:string,
		name:string,
		shortname:string
	}

	@Component({
		components: {
			OperationFileList,
			Loading,
			Distribution: resolve => (require([ "@/components/repairSteps/distribution.vue" ], resolve)),
			Normal: resolve => (require([ "@/components/repairSteps/normal.vue" ], resolve)),
			Evaluate: resolve => (require([ "@/components/repairSteps/evaluate.vue" ], resolve)),
			Bill: resolve => (require([ "@/components/repairSteps/bill.vue" ], resolve)),
			Button,
			OperationStep,
			Table
		},
		filters: {
			getTimeString (value:Date | undefined):string {
				if (typeof value === "undefined") {
					return "暂未指定";
				} else {
					return moment(value).format("YYYY-MM-DD");
				}
			}
		}
	})
	export default class OperationRoot extends Vue {
		type:string = "Loading";
		loading:boolean = true;
		errorSpaceString:string = "";
		data:{ [ other:string ]:string | undefined | Array<number> | Date } = {
			stepName: undefined,
			element: undefined,
			errorSpace: [],
			priority: undefined,
			template: undefined,
			principal: undefined,
			createTime: undefined,
			deadline: undefined,
			attitude: undefined,
			quality: undefined,
			timeliness: undefined,
			device: [],
			creator: ""
		};
		templateArray:{ text:string, value:number }[] = [];
		step:step[] = [];
		spares:{ name:string, number:number }[] = [];
		btnList:{ value:"" | number, text:string }[] = [ { value: "", text: "确认" } ];
		file:file[] = [];
		columns = [
			{
				title: "名称",
				key: "name"
			},
			{
				title: "数量",
				key: "number"
			}
		];
		private MainLink:HTMLLinkElement = document.createElement("link");

		get templateName ():any {
			// const value = this.data.template;
			// if (typeof value !== "string") {
			// 	return "";
			// } else {
			// 	if (/^\d+$/.test(value)) {
			// 		const id:number = Number(value);
			// 		const template = this.templateArray.find(t => t.value === id);
			// 		if (template) {
			// 			return template.text;
			// 		} else {
			// 			return "";
			// 		}
			// 	} else {
			// 		return value;
			// 	}
			// }
			return this.data.template_name;
		}

		private get id ():string {
			return this.$route.params.id;
		}

		submit (oid:string = "") {
			const data:any = (this.$refs.operation as any).getInfo(oid);
			this.loading = true;
			request({
				url: "/repair/eventopt/",
				method: "post",
				data,
				[ this.type === "bill" ? "" : "transformRequest" ]: [ function (data:any) {
					return qs.stringify(data, { encode: false, arrayFormat: "brackets" });
				} ]
			}).then(() => {
				this.$router.go(-1);
			});
		}

		mounted () {
			this.renderCss();
			let stepId:number;
			let stepIdURL:string;
			request({
				url: `/repair/rest/projectevent/${ this.id }/`
			}).then(({ data }) => {
				if (data.status.toString() === "4" && this.$route.name === "operation") {
					// @ts-ignore
					Message.info("维修单已处理完毕！");
					this.$router.go(-1);
					return;
				}
				this.data = {
					stepName: "分析分配",
					element: data.element,
					errorSpace: [],
					priority: data.priority,
					template: (():string | undefined => {
						if (/watch/.test(this.$route.fullPath)) {
							return data.template_name;
						} else {
							return data.template === null ? "暂未分配" : data.template.match(/\/\d+\//)[ 0 ].replace(/\//g, "");
						}
					})(),
					template_name:data.template_name,
					principal: "",
					createTime: new Date(data.createtime),
					deadline: data.createtime ? new Date(data.createtime) : undefined,
					attitude: data.attitude || 2,
					quality: data.kpi || 2,
					timeliness: data.speed || 2,
					device: [],
					creator: data.createusername
				};
				if (data.dbidlist && data.dbidlist.length > 0) {
					const temp = JSON.stringify(data.dbidlist);
					const results = temp.match(/{"roomguid":.+?}/);
					if (results) {
						const uniqueId = JSON.parse(results[ 0 ]).roomguid;
						request({
							url: "/space/room/",
							params: {
								room_guid: uniqueId
							}
						}).then(({ data }) => {
							const temp = data.results[ 0 ];
							this.$store.commit("findRoom", {
								floor: temp.floorid,
								id: uniqueId,
								path: [ temp.floorfacilityid, temp.floorid, temp.id ]
							});
						});
					}
				}
				stepId = data.curflowstep_html;
				stepIdURL = data.curflowstep ? data.curflowstep.match(/\/\d+\//)[ 0 ].replace(/\//g, "") : "";
			}).then(() => {
				request(`/repair/event/${ this.id }/info/`).then(({ data }) => {
					const info = data.data.event;
					this.errorSpaceString = info.equipment;
					const line:step[] = [];
					line.push({
						name: /自动生成/.test(info.createuser) ? "维保策略自动生成" : "创建工单",
						apart: [
							{
								operator: info.createuser,
								description: info.describe,
								doc: info.createfile,
								voice: info.voicedoc_id,
								completeTime: info.createtime,
								how: ""
							}
						]
					});
					if (Array.isArray(info.beforestep)) {
						info.beforestep.forEach((t:any) => {
							line.push({
								name: t.name,
								apart: t.opt.map((t:any) => ({
									operator: t.actor,
									description: t.comment,
									doc: t.files,
									voice: t.voice,
									completeTime: t.oprtime,
									editable: t.editable,
									id: t.id
								}))
							});
						});
					}
					/* if (typeof this.data.stepName === "string" && this.data.stepName.length > 0) {
						line.push({ name: this.data.stepName });
					} */
					if (Array.isArray(info.behindstep) && info.behindstep.length > 0 && info.behindstep[ 0 ] !== this.data.stepName) {
						line.push({ name: info.behindstep[ 0 ] });
					}
					if (Array.isArray(info.spares) && info.spares.length > 0) {
						this.spares = info.spares;
						this.spares.push({ name: "总额", number: info.maintainFee });
					}
					this.step = line;
					this.data.errorSpace = info.space || [];
					this.data.device = info.devicePath || [];
					if (this.data.template === "暂未分配") {
						this.data.template = info.template_id;
					}
					if (stepId) {
						request({
							url: `/repair/rest/flowtemplatestep/${ stepIdURL }/`
						}).then(({ data }) => {
							let type = "";
							switch (stepId.toString()) {
								case "0":
									type = "normal";
									break;
								case "1":
									type = "evaluate";
									break;
								case "2":
									type = "distribution";
									break;
								case "3":
									type = "bill";
									break;
							}
							this.type = type;
							this.data.stepName = data.name;
							this.data.principal = data.actorname ? data.actorname.join() : "暂无负责人";
							this.loading = false;
						});
					} else if (this.$route.name !== "detail") {
						this.type = "distribution";
						this.data.principal = "暂无负责人";
						this.loading = false;
					} else {
						this.loading = false;
					}

					const value:number[] = info.devicePath || [];
					if (value.length > 1) {
						request({
							url: `/device/devicecategory/${ value[ 1 ] }/`
						}).then(({ data }) => {
							(data.files.length > 0) && (this.file = this.file.concat(data.files));
						});
						request({
							url: "/file/rest/doc2relate/",
							params: {
								relatetype: "systemtype",
								relateid: value[ 0 ]
							}
						}).then(({ data }) => {
							(data.length > 0) && (this.file = this.file.concat(data));
						});
					}
					if (value.length > 2) {
						request({
							url: "/file/rest/doc2relate/",
							params: {
								relateid: value[ 2 ],
								relatetype: "device"
							}
						}).then(({ data }) => {
							(data[ 0 ].document.length > 0) && (this.file = this.file.concat(data[ 0 ].document));
						});
					}
				});
			});
			request({
				url: "/repair/flowopt/",
				params: {
					type: /repair/.test(this.$route.path) ? "wx" : "wb"
				}
			}).then(({ data }) => {
				data.data.forEach((value:any) => {
					if (!/报警/.test(value.name)) {
						this.templateArray.push({ text: value.name, value: value.id });
					}
				});
			});
			request({
				url: `/repair/event/${ this.id }/flowstepoperation/`
			}).then(({ data }) => {
				if (data.res === "succ") {
					if (this.$route.name === "deviceEdit") {
						this.btnList = [ { value: 0, text: "修改" } ];
					} else {
						this.btnList = data.data.map((t:any) => ({ value: t.id, text: t.name }));
					}
				}
			});
		}

		@Watch("$store.state.baseColor")
		onColorChange () {
			this.renderCss();
		}

		beforeRouteLeave (from:Route, to:Route, next:Function):void {
			this.MainLink.remove();
			next();
		}

		private renderCss () {
			less.render(lessFiles.operation, {
				javascriptEnabled: true,
				modifyVars: {
					"@baseColor": this.$store.state.baseColor,
					"path": "/static/UnityWeb/desktop/"
				},
				paths: [ "/static/UnityWeb/desktop/" ]
			}).then(data => {
				this.MainLink && this.MainLink.remove();
				const href:string = URL.createObjectURL(new Blob([ data.css ]));
				const link = document.createElement("link");
				link.href = href;
				link.rel = "stylesheet";
				document.head.appendChild(link);
				this.MainLink = link;
			});
		}
	}
</script>
